<template>
  <div class="custom-table-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <!-- 项目信息开始 -->
        <div class="areaCart">
          <div class="projectName">
            {{ projectInfo.projectName }}
          </div>
          <div class="projectDescription">
            项目介绍：
            <br />
            {{ projectInfo.projectDescription }}
          </div>
          <div class="projectOperation">
            <el-link
              class="operateBtn"
              icon="el-icon-edit"
              @click="handleEditProjectInfo()"
            >
              编辑
            </el-link>

            <el-link
              class="operateBtn"
              icon="el-icon-delete"
              @click="handleDeleteProjectInfo()"
            >
              删除
            </el-link>
          </div>
        </div>
        <!-- 项目信息结束 -->

        <!-- 其他操作开始 -->
        <div class="areaCart otherOperation">
          <div class="otherOperationItem">
            <i class="el-icon-plus"></i>
            <el-link
              class="operationBtn"
              type="info"
              @click="HandleAddCNameSpace"
            >
              添加Namespace
            </el-link>
          </div>
          <div class="otherOperationItem">
            <i class="el-icon-s-grid"></i>
            <el-link
              class="operationBtn"
              type="info"
              @click="QueryConfigFileInfo()"
            >
              查看配置文件信息
            </el-link>
          </div>

          <div class="otherOperationItem">
            <i class="el-icon-document"></i>
            <el-link
              class="operationBtn"
              type="info"
              @click="handleConfigFileInfo()"
            >
              一键生成json文件
            </el-link>
          </div>
        </div>

        <!-- 其他操作结束 -->
      </el-col>

      <el-col :span="20">
        <div>
          <el-collapse v-model="activeNames">
            <el-collapse-item
              v-for="(item, cIndex) in cNameSpaceList"
              :key="cIndex"
              class="nameSpaceCol"
              :name="item.id"
            >
              <template slot="title">
                <div
                  class="collapseTitle"
                  @click="handleQueryConfigInfo(item.id, true)"
                >
                  <span class="addConfigInfoSpan" @click="stopProp">
                    <el-button plain type="primary" @click="handleAdd(item.id)">
                      新增配置
                    </el-button>
                    <el-button
                      v-if="!item.isPublish"
                      plain
                      type="warning"
                      @click="publishConfigInfo(item.id)"
                    >
                      发布配置
                    </el-button>
                    <el-button
                      plain
                      type="danger"
                      @click="
                        HandleDeleteCNameSpace({
                          CNameSpace: item.nameSpace,
                          ID: item.id,
                        })
                      "
                    >
                      删除配置
                    </el-button>
                    <el-button
                      plain
                      type="success"
                      @click="OpenVersionForm(item)"
                    >
                      历史版本
                    </el-button>
                  </span>
                  <span class="nameSpaceLable">NameSpace：</span>
                  <span class="nameSpaceSpan">
                    {{ item.nameSpace }}
                  </span>
                </div>
              </template>
              <div>
                <el-table
                  :key="changeIndex"
                  :border="border"
                  :data="item.configInfos"
                  @selection-change="setSelectRows"
                >
                  <el-table-column
                    v-for="(configInfoItem, index) in finallyColumns"
                    :key="index"
                    align="center"
                    :label="configInfoItem.label"
                    :prop="configInfoItem.prop"
                    :sortable="configInfoItem.sortable"
                    :width="configInfoItem.width"
                  >
                    <template #default="{ row }">
                      <span
                        v-if="configInfoItem.label === 'Value'"
                        @click="SeeValueDetail(row[configInfoItem.prop])"
                      >
                        {{ row[configInfoItem.prop] }}
                      </span>
                      <span v-else-if="configInfoItem.label === '状态'">
                        <el-tag
                          v-if="row[configInfoItem.prop] === 1"
                          type="success"
                        >
                          已发布
                        </el-tag>
                        <el-tag
                          v-else-if="row[configInfoItem.prop] === 2"
                          type="primary"
                        >
                          增
                        </el-tag>
                        <el-tag
                          v-else-if="row[configInfoItem.prop] === 3"
                          type="danger"
                        >
                          删
                        </el-tag>
                        <el-tag v-else type="info">改</el-tag>
                      </span>
                      <span v-else>
                        {{ row[configInfoItem.prop] }}
                      </span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    align="center"
                    fixed
                    label="操作"
                    show-overflow-tooltip
                    width="85"
                  >
                    <template #default="{ row }">
                      <el-button type="text" @click="handleEdit(row)">
                        编辑
                      </el-button>
                      <el-button
                        v-if="row.state != 3"
                        type="text"
                        @click="handleDelete(row)"
                      >
                        删除
                      </el-button>
                      <el-button
                        v-if="row.state === 3"
                        type="text"
                        @click="handleRestore(row)"
                      >
                        还原
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-col>

      <project-edit-form ref="projectInfoEdit" @fetch-data="fetchData" />
      <add-c-name-space-form
        ref="addCNameSpaceForm"
        @fetch-data="queryCNameSpace"
      ></add-c-name-space-form>

      <version-form
        ref="versionForm"
        @fetch-data="reloadConfigInfo"
      ></version-form>

      <add-config-info-form
        ref="addConfigInfoForm"
        @fetch-data="reloadConfigInfo"
      ></add-config-info-form>
      <edit-config-info-form
        ref="editConfigInfoForm"
        @fetch-data="reloadConfigInfo"
      ></edit-config-info-form>

      <div>
        <el-drawer
          direction="rtl"
          size="50%"
          title="配置文件生成详情"
          :visible.sync="isConfigFileInfo"
        >
          <el-table :data="configFileInfoData">
            <el-table-column label="文件名称" property="fileName" width="230" />
            <el-table-column label="扩展名" property="exFileName" width="180" />
            <el-table-column
              label="创建时间"
              property="createTime"
              width="230"
            />
            <el-table-column
              label="修改时间"
              property="modifyTime"
              width="230"
            />
          </el-table>
        </el-drawer>
      </div>

      <!-- Value对话框开始 -->
      <el-dialog title="Value" :visible.sync="valueDialogVisibal" width="50%">
        <span>{{ valueDialogText }}</span>
        <span slot="footer" class="dialog-footer"></span>
      </el-dialog>
      <!-- Value对话框结束 -->
    </el-row>
  </div>
</template>

<script>
  import {
    GetProjectConfigs,
    DeleteProjectInfo,
    GenerateConfigFileInfo,
  } from '@/api/projectConfig/projectInfo'
  import {
    GetCNameSpaceList,
    DeleteCNameSpace,
    PublishConfigInfo,
  } from '@/api/projectConfig/cNameSpace'
  import {
    DeleteConfigInfo,
    GetConfigInfoByNameSpaceID,
    GetConfigFileInfo,
    RestoreConfigInfo,
  } from '@/api/projectConfig/configInfo'

  import ProjectEditForm from './projectInfoComponents/editProjectInfoForm.vue'
  import AddConfigInfoForm from './configInfoComponents/addConfigInfoForm.vue'
  import EditConfigInfoForm from './configInfoComponents/editConfigInfoForm.vue'
  import AddCNameSpaceForm from './cnameSpaceComponents/addCNameSpaceForm.vue'
  import VersionForm from './cnameSpaceComponents/versionsForm.vue'

  export default {
    name: 'CustomTable',
    components: {
      ProjectEditForm,
      AddCNameSpaceForm,
      AddConfigInfoForm,
      EditConfigInfoForm,
      VersionForm,
    },
    data() {
      return {
        border: true,
        checkList: ['Key', 'Value', '描述', '状态'],
        columns: [
          {
            label: 'id',
            width: 'auto',
            prop: 'id',
          },
          {
            label: 'Key',
            width: '250',
            prop: 'configKey',
          },
          {
            label: 'Value',
            width: '500',
            prop: 'configValue',
          },
          {
            label: '描述',
            width: '300',
            prop: 'configDescription',
          },
          {
            label: '状态',
            width: '100',
            prop: 'state',
          },
        ],
        cNameSpaceList: [],
        selectRows: '',
        queryForm: {
          // 项目编号
          id: '',
          nameSpaceID: '',
        },
        // 项目信息
        projectInfo: {
          projectID: '',
          projectName: '',
          projectDescription: '',
        },
        // 刷新表格时使用
        changeIndex: 0,
        // 是否展示配置文件信息
        isConfigFileInfo: false,
        // 配置文件信息列表
        configFileInfoData: [],
        activeNames: [],
        // 查看Value详情弹框是否显示
        valueDialogVisibal: false,
        // 查看Value详情弹框显示内容
        valueDialogText: '',
      }
    },
    computed: {
      finallyColumns() {
        return this.columns.filter((item) =>
          this.checkList.includes(item.label)
        )
      },
    },
    created() {
      this.queryForm.id = this.$route.query.id
      this.fetchData()
      this.queryCNameSpace()
    },
    methods: {
      setSelectRows(val) {
        this.selectRows = val
      },
      // 阻止事件传播
      stopProp(e) {
        e.stopPropagation()
      },
      // 新增配置信息
      handleAdd(nameSpaceID) {
        this.$refs['addConfigInfoForm'].showForm({
          projectID: this.queryForm.id,
          nameSpaceID: nameSpaceID,
        })
      },
      // 编辑配置信息
      handleEdit(row) {
        this.$refs['editConfigInfoForm'].showForm(row)
      },
      // 删除配置信息
      handleDelete(row) {
        this.$baseConfirm(
          '你确定要删除' + row.configKey + '吗？',
          null,
          async () => {
            DeleteConfigInfo({ ID: row.id }).then((res) => {
              if (res.data) {
                this.$baseMessage(res.msg, 'success')
                this.reloadConfigInfo(row.nameSpaceID)
              } else {
                this.$baseMessage(res.msg, 'error')
              }
            })
          }
        )
      },
      // 还原配置信息
      handleRestore(row) {
        if (row.state != 3) {
          this.$baseMessage('该配置不满足还原条件', 'error')
          return
        }
        RestoreConfigInfo({ ID: row.id }).then((res) => {
          if (res.data) {
            this.$baseMessage(res.msg, 'success')
            this.reloadConfigInfo(row.nameSpaceID)
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },
      // 发布配置文件
      publishConfigInfo(nameSpaceID) {
        PublishConfigInfo({ NameSpaceID: nameSpaceID }).then((res) => {
          if (res.data) {
            this.reloadConfigInfo(nameSpaceID)
            this.$baseMessage(res.msg, 'success')
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },
      // 获取项目信息
      async fetchData() {
        var resInfo = await GetProjectConfigs(this.queryForm)
        this.projectInfo = resInfo.data
      },
      //修改项目信息
      handleEditProjectInfo() {
        this.$refs['projectInfoEdit'].showForm(this.projectInfo)
      },
      // 删除项目信息
      handleDeleteProjectInfo() {
        this.$baseConfirm(
          '你确定要删除' + this.projectInfo.projectName + '吗？',
          null,
          async () => {
            DeleteProjectInfo({ ID: this.projectInfo.projectID }).then(
              (res) => {
                if (res.data) {
                  this.$baseMessage(res.msg, 'success')
                  // 删除成功跳转到项目信息界面
                  this.$router.push({ path: '/projectInfoIndex' })
                } else {
                  this.$baseMessage(res.msg, 'error')
                }
              }
            )
          }
        )
      },
      // 添加NameSpace
      HandleAddCNameSpace() {
        this.$refs['addCNameSpaceForm'].showEdit(this.queryForm.id)
      },
      // 历史版本
      OpenVersionForm(cNameSpace) {
        this.$refs['versionForm'].ShowForm(cNameSpace)
      },
      // 删除NameSpace
      HandleDeleteCNameSpace(cNameSpace) {
        this.$baseConfirm(
          '你确定要删除【' +
            cNameSpace.CNameSpace +
            '】吗？该操作不可逆，请谨慎操作！',
          null,
          async () => {
            DeleteCNameSpace({ ID: cNameSpace.ID }).then((res) => {
              if (res.data) {
                this.$baseMessage(res.msg, 'success')
                this.queryCNameSpace()
              } else {
                this.$baseMessage(res.msg, 'error')
              }
            })
          }
        )
      },
      // 获取命名空间列表
      queryCNameSpace() {
        GetCNameSpaceList({ projectID: this.queryForm.id }).then((res) => {
          this.cNameSpaceList = res.data
          this.activeNames = []
        })
      },
      // 点击NameSpace折叠面板，获取配置信息
      handleQueryConfigInfo(id) {
        var index = this.cNameSpaceList.findIndex(
          (nameSpace) => nameSpace.id == id
        )

        if (index < 0) {
          return
        }

        var nameSpaceObj = this.cNameSpaceList[index]
        if (
          nameSpaceObj.configInfos == null ||
          nameSpaceObj.configInfos == undefined
        ) {
          GetConfigInfoByNameSpaceID({
            NameSpaceID: nameSpaceObj.id,
          }).then((res) => {
            nameSpaceObj.configInfos = res.data
            this.changeIndex++
          })
        }
      },
      // 从新加载配置信息
      reloadConfigInfo(id) {
        var index = this.cNameSpaceList.findIndex(
          (nameSpace) => nameSpace.id == id
        )
        if (index >= 0) {
          var nameSpaceObj = this.cNameSpaceList[index]
          GetConfigInfoByNameSpaceID({
            NameSpaceID: nameSpaceObj.id,
          }).then((res) => {
            nameSpaceObj.configInfos = res.data

            var isPublish = true
            nameSpaceObj.configInfos.forEach((item) => {
              if (item.state != 1) {
                isPublish = false
                return false
              }
            })

            nameSpaceObj.isPublish = isPublish

            this.changeIndex++
          })
        }
      },
      // 获取生成.json文件信息
      QueryConfigFileInfo() {
        GetConfigFileInfo({ ProjectID: this.queryForm.id }).then((res) => {
          if (res.data != null && res.data != undefined) {
            this.configFileInfoData = res.data
            this.isConfigFileInfo = true
          }
        })
      },
      // 生成json
      handleConfigFileInfo() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })

        GenerateConfigFileInfo({
          ProjectID: this.projectInfo.projectID,
        }).then((res) => {
          if (res.data) {
            this.$baseMessage(res.msg, 'success')
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })

        setTimeout(() => {
          loading.close()
        }, 1000)
      },
      //查看Value详情
      SeeValueDetail(value) {
        this.valueDialogVisibal = true
        this.valueDialogText = value
      },
    },
  }
</script>

<style lang="scss" scoped>
  .custom-table-container {
    margin-top: 10px;
    padding: 0;
  }

  // 项目介绍样式开始
  .areaCart {
    margin-left: 10px;
    background-color: #fff;
  }

  .projectName,
  .projectDescription,
  .projectOperation {
    width: 100%;
    display: inline-block;
  }

  .projectName {
    font-size: 16px;
    // 文字自动换行
    word-wrap: break-word;
    padding-top: 20px;
    padding-bottom: 15px;
    border-bottom: #000 1px solid;
  }
  .projectDescription {
    margin-top: 10px;
    font-size: 14px;
    // 文字自动换行
    word-wrap: break-word;
    padding-bottom: 20px;
  }
  .projectOperation {
    padding-bottom: 10px;
  }
  .operateBtn {
    margin-right: 40px;
    padding-bottom: 10px;
  }
  // 项目介绍样式结束

  // 其他操作样式开始
  .otherOperation {
    font-size: 30px;
    background-color: rgb(246, 248, 249);
  }
  .otherOperationItem {
    height: 50px;
    line-height: 50px;
    padding-left: 20px;
    margin-top: 5px;
    background-color: #fff;
  }
  .operationBtn {
    margin-left: 10px;
  }
  // 其他操作样式结束

  // 配置信息样式开始
  .nameSpaceCol {
    margin-bottom: 20px;
  }
  .collapseTitle {
    border-bottom: #c4c4c4 solid 1px;
    width: 100%;
    line-height: 44px;
  }
  .nameSpaceLable {
    margin-left: 10px;
    font-size: 20px;
    font-weight: bolder;
  }
  .nameSpaceSpan {
    font-size: 18px;
  }
  .addConfigInfoSpan {
    margin-left: 20px;
  }
  // 配置信息样式结束
</style>
